#include "QAdwiceDialog.h"

QAdwiceDialog::QAdwiceDialog(QPixmap icon,QString filename,QWidget * parent):QDialog(parent,Qt::SplashScreen)
{
	this->setWindowTitle(trUtf8("Trucs à savoir?"));
	this->setFixedSize(500,400);
	
	QVBoxLayout * vlayout=new QVBoxLayout(this);
	QHBoxLayout * hlayout=new QHBoxLayout();
	QHBoxLayout * hlayout2=new QHBoxLayout();

	l_adwice=new QTextEdit(this);
	cb_showAdwice=new QCheckBox(trUtf8("Ne plus montrer les conseils au démarrage de Clémentine"),this);
	pb_close=new QPushButton("Fermer",this);
	pb_next=new QPushButton("Suivant",this);
	l_pix=new QLabel(this);
	l_pix->setPixmap(icon);

	QFont font("Times", 20, QFont::Bold);
	l_title=new QLabel(trUtf8("Clémentine 2.00"));
	l_title->setFont(font);
	
	vlayout->addSpacing(10);	
	hlayout->addStretch();
	hlayout->addWidget(l_pix);
	hlayout->addWidget(l_title);
	hlayout->addStretch();
	vlayout->addLayout(hlayout);
	vlayout->addSpacing(20);
	vlayout->addWidget(l_adwice);
	vlayout->addSpacing(20);
	vlayout->addWidget(cb_showAdwice);
	hlayout2->addStretch();
	hlayout2->addWidget(pb_close);
	hlayout2->addWidget(pb_next);
	vlayout->addLayout(hlayout2);

	this->filename=filename;

	QFile file(filename);
	if(file.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QTextStream in(&file);
		cb_showAdwice->setChecked(in.readLine().toInt());

		while(!in.atEnd())
		{
			adwice_list+=in.readLine();
		}
		file.close();
	}
	else
	{
		printf("Erreur : Impossible de trouver le fichier des conseils");
	}
	
	connect(pb_close,SIGNAL(clicked()),this,SLOT(close()));
	connect(pb_next,SIGNAL(clicked()),this,SLOT(s_next()));

	currentid=rand()%(adwice_list.size());
	l_adwice->setText(adwice_list[currentid]);
}

void QAdwiceDialog::s_next()
{
	currentid++;
	if(currentid>=(unsigned int)adwice_list.size())currentid=0;
	l_adwice->setText(adwice_list[currentid]);

	adjustSize();
}

void QAdwiceDialog::closeEvent(QCloseEvent * event)
{
	QFile file(filename);
	if(file.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QTextStream in(&file);
		in<<cb_showAdwice->isChecked()<<"\n";

		for(unsigned int i=0;i<adwice_list.size();i++)
		{
			in<<adwice_list[i]<<"\n";
		}
		file.close();
	}
	else
	{
		printf("Erreur : Impossible de trouver le fichier des conseils");
	}
}

bool QAdwiceDialog::isAsked()
{
	return !((bool)cb_showAdwice->isChecked());
}
